import os
import datetime
import logging
from logging.handlers import BaseRotatingHandler


class DayRotatingHandler(BaseRotatingHandler):
    def __init__(self, filename, mode='a', encoding=None, delay=False, suffix="%Y-%m-%d.log"):
        self.current_date = datetime.date.today()  # 当前日期
        self.base_dir, self.base_filename = os.path.split(filename)  # 分离目录和文件名
        self.suffix = suffix
        # 确保日志目录存在
        os.makedirs(self.base_dir, exist_ok=True)
        super().__init__(filename, mode, encoding=encoding, delay=delay)

    def should_rollover(self):
        """检查是否需要滚动日志（日期是否变化）"""
        return self.current_date != datetime.date.today()

    def do_rollover(self):
        try:
            if self.stream:
                self.stream.close()
                self.stream = None

            # 更新当前日期
            self.current_date = datetime.date.today()
            # 生成新的日志文件名
            new_log_file = os.path.join(
                self.base_dir,
                self.current_date.strftime(self.suffix))
            self.baseFilename = new_log_file
            self._open()  # 重新打开日志文件
        except Exception as e:
            print(f"Failed to rollover log file: {e}")

    def emit(self, record):
        try:
            if self.should_rollover():
                self.do_rollover()

            # 确保 self.stream 是有效的
            if self.stream is None:
                self._open()

            # 格式化日志记录
            msg = self.format(record)
            # 写入日志文件
            self.stream.write(msg + self.terminator)
            self.flush()
        except Exception as e:
            print(f"Failed to emit log record: {e}")
            self.handleError(record)


log_dir = r"D:\python_project\vue-flask-app\api\logs"

# 创建 DayRotatingHandler 实例
handler = DayRotatingHandler(os.path.join(log_dir, "app.log"))
handler.setLevel(logging.INFO)

# 设置日志格式
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# 创建日志记录器并设置级别
logger = logging.getLogger("my_logger")
logger.setLevel(logging.INFO)
logger.addHandler(handler)

# 测试日志
# logger.info("This is a test log message.")
# logger.warning("warning")
# logger.error("error")
